<!DOCTYPE html>
<html lang="zh" xmlns:th="http://www.thymeleaf.org">
<head>
    <th:block th:include="include :: header('标注历史详情')" />
    <style>
        .annotation-form {
            background-color: #f8f9fa;
            padding: 20px;
            border-radius: 5px;
            margin-bottom: 20px;
        }
        .comment-item {
            border-bottom: 1px solid #eee;
            padding: 15px 0;
        }
        .comment-item:last-child {
            border-bottom: none;
        }
        .comment-header {
            margin-bottom: 8px;
            color: #666;
            font-size: 12px;
        }
        .comment-content {
            margin-left: 20px;
            color: #333;
        }
        .comment-input {
            margin-top: 20px;
        }
        .image-preview {
            width: 100%;
            height: auto;
            max-height: calc(100vh - 200px);
            padding: 2px;
            object-fit: contain;
            display: none;
            cursor: pointer;
            border: 1px solid #ddd;
            border-radius: 4px;
            background-color: #fff;
        }
        
        /* Loading动画样式 */
        .loading-container {
            display: flex;
            flex-direction: column;
            align-items: center;
            justify-content: center;
            padding: 40px 20px;
            background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);
            border-radius: 12px;
            box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1);
            backdrop-filter: blur(10px);
            border: 1px solid rgba(255, 255, 255, 0.2);
            min-width: 200px;
            min-height: 150px;
        }
        
        .loading-spinner {
            position: relative;
            width: 60px;
            height: 60px;
            margin-bottom: 20px;
        }
        
        .spinner-ring {
            position: absolute;
            width: 100%;
            height: 100%;
            border: 3px solid transparent;
            border-radius: 50%;
            animation: spin 1.5s linear infinite;
        }
        
        .spinner-ring:nth-child(1) {
            border-top-color: #3498db;
            animation-duration: 1.2s;
        }
        
        .spinner-ring:nth-child(2) {
            border-right-color: #e74c3c;
            animation-duration: 1.4s;
            animation-delay: 0.2s;
        }
        
        .spinner-ring:nth-child(3) {
            border-bottom-color: #f39c12;
            animation-duration: 1.6s;
            animation-delay: 0.4s;
        }
        
        .spinner-ring:nth-child(4) {
            border-left-color: #2ecc71;
            animation-duration: 1.8s;
            animation-delay: 0.6s;
        }
        
        @keyframes spin {
            0% {
                transform: rotate(0deg) scale(1);
                opacity: 1;
            }
            50% {
                transform: rotate(180deg) scale(1.1);
                opacity: 0.8;
            }
            100% {
                transform: rotate(360deg) scale(1);
                opacity: 1;
            }
        }
        
        .loading-text {
            font-size: 16px;
            font-weight: 500;
            color: #2c3e50;
            text-align: center;
            animation: pulse 2s ease-in-out infinite;
            margin-top: 10px;
        }
        
        @keyframes pulse {
            0%, 100% {
                opacity: 0.7;
                transform: translateY(0);
            }
            50% {
                opacity: 1;
                transform: translateY(-3px);
            }
        }
        .detail-info {
            background-color: #f8f9fa;
            padding: 15px;
            border-radius: 5px;
            margin-bottom: 20px;
        }
        .info-item {
            margin-bottom: 10px;
        }
        .info-label {
            font-weight: bold;
            color: #555;
            width: 100px;
            display: inline-block;
        }
        
        /* 图片切换箭头按钮样式 */
        .image-nav-arrow {
            position: absolute;
            top: 50%;
            transform: translateY(-50%);
            width: 40px;
            height: 40px;
            background-color: rgba(0, 0, 0, 0.5);
            color: white;
            border: none;
            border-radius: 50%;
            font-size: 20px;
            cursor: pointer;
            display: flex;
            align-items: center;
            justify-content: center;
            z-index: 10;
            transition: all 0.3s ease;
        }
        
        .image-nav-arrow:hover:not(:disabled) {
            background-color: rgba(0, 0, 0, 0.7);
            transform: translateY(-50%) scale(1.1);
        }
        
        .image-nav-arrow:disabled {
            background-color: rgba(128, 128, 128, 0.3);
            cursor: not-allowed;
            opacity: 0.5;
        }
        
        .image-nav-arrow.prev {
            left: 10px;
        }
        
        .image-nav-arrow.next {
            right: 10px;
        }
    </style>
</head>
<body class="white-bg">
    <div class="wrapper wrapper-content animated fadeInRight">
        <div class="row">
            <div class="col-sm-12">
                <div class="ibox">
                    <div class="ibox-title">
                        <h5>标注历史详情</h5>
                        <div class="ibox-tools">
                            <a class="collapse-link">
                                <i class="fa fa-chevron-up"></i>
                            </a>
                            <a class="close-link" onclick="$.modal.close()">
                                <i class="fa fa-times"></i>
                            </a>
                        </div>
                    </div>
                    <div class="ibox-content">
                        <div class="row">
                            <div class="col-sm-5">
                                <div class="text-center" style="display: flex; flex-direction: column; align-items: center; min-height: 400px; justify-content: center; position: relative;">
                            <!-- 图片切换箭头按钮 -->
                            <button id="prevImageBtn" class="image-nav-arrow prev" onclick="switchToPrevImage()" disabled>
                                <i class="fa fa-angle-left"></i>
                            </button>
                            <button id="nextImageBtn" class="image-nav-arrow next" onclick="switchToNextImage()" disabled>
                                <i class="fa fa-angle-right"></i>
                            </button>
                            
                            <!-- 图片预览 -->
                            <img id="previewImage" class="image-preview" alt="图片预览" onclick="showFullPreview()">
                            <!-- Loading动画 -->
                            <div id="loadingMessage" class="loading-container">
                                <div class="loading-spinner">
                                    <div class="spinner-ring"></div>
                                    <div class="spinner-ring"></div>
                                    <div class="spinner-ring"></div>
                                    <div class="spinner-ring"></div>
                                </div>
                                <div class="loading-text">正在加载图片...</div>
                            </div>
                            <div style="margin-top: 10px;">
                                <button type="button" class="btn btn-primary btn-sm" onclick="showFullPreview()">
                                    <i class="fa fa-search-plus"></i> 查看大图
                                </button>
                            </div>
                        </div>
                            </div>
                            <div class="col-sm-7">
                                <!-- 标注信息部分 -->
                                <form id="annotationForm" class="annotation-form">
                                    <h4>标注信息</h4>
                                    <input type="hidden" id="pictureIdInput" name="id">
                                    <div class="form-group">
                                        <label class="control-label">左脚诊断：</label>
                                        <select id="leftFoot" name="leftFoot" class="form-control" required>
                                        </select>
                                    </div>
                                    <div class="form-group">
                                        <label class="control-label">右脚诊断：</label>
                                        <select id="rightFoot" name="rightFoot" class="form-control" required>
                                        </select>
                                    </div>
                                    <div class="form-group">
                                        <label class="control-label">腿型分类：</label>
                                        <select id="leg" name="leg" class="form-control" required>
                                        </select>
                                    </div>
                                    <div class="form-group">
                                        <button type="button" class="btn btn-primary" onclick="saveAnnotation()">
                                            <i class="fa fa-save"></i> 保存修改
                                        </button>
                                    </div>
                                </form>
                                
                                <!-- 评论列表部分 -->
                                <div class="ibox" style="margin-top: 20px;">
                                    <div class="ibox-title">
                                        <h5>评论列表</h5>
                                    </div>
                                    <div class="ibox-content">
                                        <div id="commentList">
                                            <div class="text-center" style="padding: 20px;">
                                                <i class="fa fa-spinner fa-spin"></i> 正在加载评论...
                                            </div>
                                        </div>
                                        
                                        <div class="comment-input">
                                            <h5>添加评论</h5>
                                            <div class="form-group">
                                                <textarea id="content" class="form-control" rows="3" placeholder="请输入评论内容..."></textarea>
                                            </div>
                                            <div class="form-group">
                                                <button type="button" class="btn btn-primary" onclick="addComment()">
                                                    <i class="fa fa-send"></i> 发表评论
                                                </button>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
    
    <!-- 大图预览弹窗 -->
    <div class="modal fade" id="imagePreviewModal" tabindex="-1" role="dialog" aria-labelledby="imagePreviewModalLabel" aria-hidden="true">
        <div class="modal-dialog modal-lg" style="width: 85%; max-width: 1000px; margin: 5% auto;">
            <div class="modal-content" style="max-height: 85vh;">
                <div class="modal-header">
                    <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>
                    <h4 class="modal-title" id="imagePreviewModalLabel">图片预览</h4>
                </div>
                <div class="modal-body text-center" style="padding: 20px; background-color: #f5f5f5; overflow: hidden; height: calc(85vh - 120px);">
                    <div style="position: relative; height: calc(85vh - 160px); display: flex; align-items: center; justify-content: center; overflow: hidden;">
                        <img id="modalPreviewImage" src="" alt="预览图片" style="max-width: 100%; max-height: 70%; cursor: grab; transition: transform 0.3s ease; position: relative; z-index: 1;">
                    </div>
                    <div style="margin-top: 15px; position: relative; z-index: 2;">
                        <button type="button" class="btn btn-default" onclick="zoomModalImage(1.2)">
                            <i class="fa fa-search-plus"></i> 放大
                        </button>
                        <button type="button" class="btn btn-default" onclick="zoomModalImage(0.8)">
                            <i class="fa fa-search-minus"></i> 缩小
                        </button>
                        <button type="button" class="btn btn-default" onclick="resetModalZoom()">
                            <i class="fa fa-refresh"></i> 重置
                        </button>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-default" data-dismiss="modal">关闭</button>
                </div>
            </div>
        </div>
    </div>
    
    <th:block th:include="include :: footer" />
    <script th:inline="javascript">
        var prefix = ctx + "system/picture";
        var commentPrefix = ctx + "system/picture/comment";
        var pictureId = [[${pictureId}]];
        var currentModalZoom = 1;
        var isDragging = false;
        var dragStartX = 0;
        var dragStartY = 0;
        var imageStartX = 0;
        var imageStartY = 0;
        
        // 存储图片ID列表和当前索引
        var pictureIds = [];
        var currentPictureIndex = -1;
        
        // 存储相邻图片ID
        var previousPictureId = null;
        var nextPictureId = null;
        
        // 存储查询条件参数
        var queryParams = {};
        // 存储当前图片的更新时间，用于查询相邻记录

        
        // 全局变量存储字典数据
        var dictData = {
            foot_type: [],
            leg_type: []
        };


        
        $(function() {
            // 获取URL中的所有查询参数
            loadQueryParams();
            
            // 加载字典数据
            loadDictData();
            // 加载图片详情
            loadPictureDetail();
            // 加载评论列表
            loadComments();
            
            // 绑定大图预览弹窗事件
            $("#imagePreviewModal").on("hidden.bs.modal", function() {
                resetModalZoom();
            });
            

            

        });
        
        // 加载所有查询参数（包括URL参数和列表页面传递的参数）
        function loadQueryParams() {
            var urlParams = new URLSearchParams(window.location.search);
            
            // 清空查询参数对象，确保没有残留数据
            queryParams = {};
            
            // 常见的筛选参数列表，确保这些参数即使在URL中不存在也能被处理
            const commonFilterParams = ['updateUserId', 'rightFoot', 'leftFoot', 'leg', 'beginTime', 'endTime'];
            
            // 1. 从URL中加载所有参数
            urlParams.forEach(function(value, key) {
                // 排除ids参数，因为我们不再依赖本地ID列表
                if (key !== 'ids') {
                    queryParams[key] = value;
                    console.log("从URL加载参数:", key, "=", value);
                }
            });
            
            // 2. 尝试从localStorage获取列表页面可能存储的筛选条件
            try {
                const listFilterParams = localStorage.getItem('pictureListFilterParams');
                if (listFilterParams) {
                    const filterData = JSON.parse(listFilterParams);
                    commonFilterParams.forEach(param => {
                        if (filterData[param] && !queryParams[param]) {
                            queryParams[param] = filterData[param];
                            console.log("从localStorage加载参数:", param, "=", filterData[param]);
                        }
                    });
                }
            } catch (e) {
                console.error("从localStorage加载筛选参数失败:", e);
            }
            
            // 3. 确保URL中始终包含必要的筛选参数，即使为空
            commonFilterParams.forEach(param => {
                if (queryParams[param] === undefined) {
                    // 如果参数不存在，显式设置为null或空字符串，确保它会被传递给后端
                    queryParams[param] = '';
                    console.log("初始化默认参数:", param, "=''");
                }
            });
            
            console.log("最终加载的查询参数:", queryParams);
        }
        
        // 构建带查询参数的URL
        function buildUrlWithParams(baseUrl, additionalParams) {
            var url = new URL(baseUrl, window.location.origin);
            var params = new URLSearchParams(url.search);
            
            // 添加基本查询参数
            Object.keys(queryParams).forEach(function(key) {
                params.set(key, queryParams[key]);
            });
            
            // 添加额外参数
            if (additionalParams) {
                Object.keys(additionalParams).forEach(function(key) {
                    params.set(key, additionalParams[key]);
                });
            }
            
            url.search = params.toString();
            return url.toString();
        }
        
        // 加载字典数据
        function loadDictData() {
            // 加载右腿诊断字典
            $.ajax({
                url: ctx + "system/dict/data/type/foot_type",
                type: "GET",
                async: false,
                success: function(result) {
                    if (result.code == web_status.SUCCESS) {
                        dictData.foot_type = result.data;
                        var options = '';
                        // 填充下拉框
                        $.each(dictData.foot_type, function(index, item) {
                            if (item.dictValue == 0) {
                                options += '<option value="' + item.dictValue + '" selected>' + item.dictLabel + '</option>';
                            } else {
                                options += '<option value="' + item.dictValue + '">' + item.dictLabel + '</option>';
                            }
                        });
                        $('#rightFoot, #leftFoot').html(options);
                    }
                }
            });
            
            // 加载腿型分类字典
            $.ajax({
                url: ctx + "system/dict/data/type/leg_type",
                type: "GET",
                async: false,
                success: function(result) {
                    if (result.code == web_status.SUCCESS) {
                        dictData.leg_type = result.data;
                        // 填充下拉框
                        var options = '';
                        $.each(dictData.leg_type, function(index, item) {
                            if (item.dictValue == 0) {
                                options += '<option value="' + item.dictValue + '" selected>' + item.dictLabel + '</option>';
                            } else {
                                options += '<option value="' + item.dictValue + '">' + item.dictLabel + '</option>';
                            }
                        });
                        $('#leg').html(options);
                    }
                }
            });
        }
        
        // 加载图片详情
        function loadPictureDetail(id) {
            // 如果没有提供ID，则使用当前的pictureId
            id = id || pictureId;
            
            $.ajax({
                url: prefix + "/" + id,
                type: "get",
                dataType: "json",
                success: function(result) {
                    if (result.code == web_status.SUCCESS) {
                        var picture = result.data;
                        // 填充基本信息
                        $('#pictureId').text(picture.id);
                        $('#updateUserName').text(picture.updateUserName || '未知用户');
                        $('#updateTime').text($.common.dateFormat(picture.updateTime, 'yyyy-MM-dd HH:mm:ss'));
                        
                        // 显示loading效果
                        $('#loadingMessage').show();
                        $('#previewImage').hide();
                        
                        // 设置图片src并监听加载事件
                        var previewImage = document.getElementById('previewImage');
                        previewImage.onload = function() {
                            // 图片加载完成后隐藏loading并显示图片
                            $('#loadingMessage').hide();
                            $('#previewImage').show();
                        };
                        previewImage.onerror = function() {
                            // 图片加载失败时显示错误信息
                            $('#loadingMessage').hide();
                            $.modal.alertError("图片加载失败");
                        };
                        previewImage.src = picture.url;
                        
                        // 填充标注信息
                        $('#pictureIdInput').val(picture.id);
                        $('#rightFoot').val(picture.rightFoot);
                        $('#leftFoot').val(picture.leftFoot);
                        $('#leg').val(picture.leg);
                        
                        // 记录当前图片更新时间，用于排序
                        currentPictureUpdateTime = picture.updateTime;
                        
                        // 加载评论
                        loadComments(picture.id);
                        
                        // 获取上一张和下一张图片的ID
                        fetchAdjacentPictureIds(picture.id, picture.updateTime);
                    } else {
                        $('#loadingMessage').hide();
                        $.modal.alertError(result.msg);
                    }
                },
                error: function() {
                    $('#loadingMessage').hide();
                    $.modal.alertError("加载图片详情失败");
                }
            });
        }
        
        // 获取相邻图片ID
        function fetchAdjacentPictureIds(currentId, updateTime) {
            // 创建参数对象，明确包含关键字段
            const params = {
                id: currentId,            // 当前图片ID，必须包含
                updateTime: updateTime    // 更新时间，用于排序
            };
            
            // 关键修改：检查参数是否存在于queryParams对象中，而不是检查其值是否为真值
            // 这确保空字符串('')等参数也能被正确传递给后端
            const filterParams = ['updateUserId', 'rightFoot', 'leftFoot', 'leg', 'beginTime', 'endTime'];
            filterParams.forEach(param => {
                if (param in queryParams) {
                    params[param] = queryParams[param];
                }
            });
            
            // 为了安全起见，仍然执行$.extend以获取可能的其他参数
            $.extend(params, queryParams);
            
            const serializedParams = $.param(params);
            
            // 重置相邻图片ID
            previousPictureId = null;
            nextPictureId = null;
            
            // 使用$.ajaxSetup临时设置全局选项，确保GET请求参数正确序列化
            $.ajaxSetup({
                traditional: true, // 确保复杂数据类型正确序列化
                cache: false       // 禁用缓存，确保每次请求都是新的
            });
            
            // 并行请求上一张和下一张图片ID
            $.when(
                // 获取上一张图片ID
                $.ajax({
                    url: prefix + "/getPreviousId",
                    type: "GET",
                    data: params,
                    // 添加错误处理
                    error: function(xhr, status, error) {
                    },
                    // 添加请求前回调，记录最终发送的请求
                    beforeSend: function(xhr, settings) {
                        console.log("发送获取上一张ID请求到:", settings.url);
                        console.log("发送的完整参数:", settings.data);
                    }
                }),
                // 获取下一张图片ID
                $.ajax({
                    url: prefix + "/getNextId",
                    type: "GET",
                    data: params,
                    // 添加错误处理
                    error: function(xhr, status, error) {
                    },

                })
            ).done(function(prevRes, nextRes) {
                // 处理上一张图片ID响应 - 适配数组格式响应 [{data}, 'success', {meta}]
                try {
                    // 检查是否是数组格式响应 [{data}, 'success', {meta}]
                    if (Array.isArray(prevRes) && prevRes.length >= 1 && prevRes[0]) {
                        // 直接使用第一个元素作为数据
                        if (prevRes[0].id) {
                            previousPictureId = prevRes[0].id;
                        } else if (prevRes[0].data && prevRes[0].data !== null && prevRes[0].data !== '') {
                            previousPictureId = prevRes[0].data;
                        } else {
                            // 尝试直接使用第一个元素
                            previousPictureId = prevRes[0] !== null && prevRes[0] !== '' ? prevRes[0] : null;
                        }
                    } else if (prevRes && prevRes.code === 200) {
                        // 兼容旧格式
                        previousPictureId = prevRes.data || null;
                    } else {
                        previousPictureId = null;
                        console.warn("上一张图片ID响应数据格式不符合预期");
                    }
                } catch (e) {
                    previousPictureId = null;
                    console.error("处理上一张图片ID响应时出错:", e);
                }
                
                // 处理下一张图片ID响应 - 适配数组格式响应 [{data}, 'success', {meta}]
                try {
                    // 检查是否是数组格式响应 [{data}, 'success', {meta}]
                    if (Array.isArray(nextRes) && nextRes.length >= 1 && nextRes[0]) {
                        // 直接使用第一个元素作为数据
                        if (nextRes[0].id) {
                            nextPictureId = nextRes[0].id;
                        } else if (nextRes[0].data && nextRes[0].data !== null && nextRes[0].data !== '') {
                            nextPictureId = nextRes[0].data;
                        } else {
                            // 尝试直接使用第一个元素
                            nextPictureId = nextRes[0] !== null && nextRes[0] !== '' ? nextRes[0] : null;
                        }
                    } else if (nextRes && nextRes.code === 200) {
                        // 兼容旧格式
                        nextPictureId = nextRes.data || null;
                    } else {
                        nextPictureId = null;
                        console.warn("下一张图片ID响应数据格式不符合预期");
                    }
                } catch (e) {
                    nextPictureId = null;
                    console.error("处理下一张图片ID响应时出错:", e);
                }
                
                // 强制更新箭头按钮状态，使用延迟确保DOM更新完成
                setTimeout(function() {
                    // 调用统一的状态更新函数，确保逻辑一致性
                    updateArrowButtonsState();
                }, 100);
            }).always(function() {
                // 恢复默认的ajax设置
                $.ajaxSetup({
                    traditional: false,
                    cache: true
                });
            });
        }
        
        // 加载评论列表
        function loadComments(pictureIdParam) {
            // 使用传入的图片ID或默认使用全局pictureId
            var id = pictureIdParam || pictureId;
            
            $.ajax({
                url: commentPrefix + "/picture/" + id,
                type: "get",
                dataType: "json",
                success: function(result) {
                    if (result.code == web_status.SUCCESS) {
                        renderComments(result.data);
                    } else {
                        $.modal.alertError(result.msg);
                    }
                },
                error: function() {
                    $.modal.alertError("加载评论失败");
                }
            });
        }
        
        // 渲染评论列表
        function renderComments(comments) {
            var html = '';
            if (comments && comments.length > 0) {
                $.each(comments, function(index, comment) {
                    html += '<div class="comment-item">';
                    html += '   <div class="comment-header">';
                    html += '       <strong>' + (comment.commentUserName || '未知用户') + '</strong>';
                    html += '       <span style="margin-left: 10px; color: #999;">' + $.common.dateFormat(comment.commentTime, 'yyyy-MM-dd HH:mm:ss') + '</span>';
                    html += '   </div>';
                    html += '   <div class="comment-content">' + comment.content + '</div>';
                    html += '</div>';
                });
            } else {
                html = '<div class="text-center" style="padding: 20px; color: #999;">暂无评论</div>';
            }
            $('#commentList').html(html);
        }
        
        // 添加评论
        function addComment() {
            var content = $('#content').val().trim();
            if (!content) {
                $.modal.alertWarning("请输入评论内容");
                return;
            }
            
            var comment = {
                pictureId: pictureId,
                content: content
            };
            
            $.ajax({
                url: commentPrefix,
                type: "post",
                contentType: "application/json",
                data: JSON.stringify(comment),
                dataType: "json",
                success: function(result) {
                    if (result.code == web_status.SUCCESS) {
                        // 更新图片的remark字段为1，表示已评论
                        $.ajax({
                            url: prefix + "/updateRemark",
                            type: "post",
                            contentType: "application/json",
                            data: JSON.stringify({id: pictureId, remark: 1}),
                            async: false // 同步请求，确保remark更新后再刷新页面
                        });
                        
                        $.modal.alertSuccess("评论发表成功");
                        $('#content').val('');
                        loadComments(); // 重新加载评论列表
                    } else {
                        $.modal.alertError(result.msg);
                    }
                },
                error: function() {
                    $.modal.alertError("发表评论失败");
                }
            });
        }
        
        // 保存标注修改
        function saveAnnotation() {
            var rightFoot = $('#rightFoot').val();
            var leftFoot = $('#leftFoot').val();
            var leg = $('#leg').val();
            
            if (rightFoot == 0 || leftFoot == 0 || leg == 0) {
                $.modal.alertWarning("请完整填写标注信息");
                return;
            }
            
            var pictureInfo = {
                id: pictureId,
                rightFoot: rightFoot,
                leftFoot: leftFoot,
                leg: leg
            };
            
            $.ajax({
                url: prefix + "/update",
                type: "post",
                contentType: "application/json",
                data: JSON.stringify(pictureInfo),
                dataType: "json",
                success: function(result) {
                    if (result.code == web_status.SUCCESS) {
                        $.modal.alertSuccess("标注修改已保存成功！");
                    } else {
                        $.modal.alertError(result.msg);
                    }
                },
                error: function() {
                    $.modal.alertError("保存标注修改失败，请重试");
                }
            });
        }
        
        
        // 显示大图预览
        function showFullPreview() {
            var imageSrc = $('#previewImage').attr('src');
            if (imageSrc) {
                $('#modalPreviewImage').attr('src', imageSrc);
                $('#imagePreviewModalLabel').text('图片预览 - ' + pictureId);
                $('#imagePreviewModal').modal('show');
                resetModalZoom();
                
                // 绑定滚轮缩放事件
                setTimeout(function() {
                    bindModalWheelEvent();
                }, 300);
            }
        }
        
        // 绑定预览图片滚轮事件
        function bindModalWheelEvent() {
            $('#modalPreviewImage').off('wheel.preview').on('wheel.preview', function(e) {
                e.preventDefault();
                var delta = e.originalEvent.deltaY;
                if (delta > 0) {
                    zoomModalImage(0.9);
                } else {
                    zoomModalImage(1.1);
                }
            });
        }
        
        // 预览图片缩放
        function zoomModalImage(factor) {
            currentModalZoom *= factor;
            currentModalZoom = Math.max(0.1, Math.min(currentModalZoom, 3));
            $('#modalPreviewImage').css('transform', 'scale(' + currentModalZoom + ')');
            
            if (currentModalZoom > 1.5) {
                $('#modalPreviewImage').css('margin-bottom', '80px');
                enableModalDrag();
            } else {
                $('#modalPreviewImage').css('margin-bottom', '0');
                disableModalDrag();
            }
        }
        
        // 重置预览缩放
        function resetModalZoom() {
            currentModalZoom = 1;
            $('#modalPreviewImage').css('transform', 'scale(1)');
            $('#modalPreviewImage').css('margin-bottom', '0');
            $('#modalPreviewImage').css({'left': '0', 'top': '0'});
            disableModalDrag();
            
            setTimeout(function() {
                bindModalWheelEvent();
            }, 100);
        }
        
        // 启用预览图片拖动
        function enableModalDrag() {
            var $img = $('#modalPreviewImage');
            $img.css('cursor', 'grab');
            
            // 初始化拖拽状态变量
            isDragging = false;
            
            $img.off('mousedown.preview').on('mousedown.preview', function(e) {
                isDragging = true;
                dragStartX = e.clientX;
                dragStartY = e.clientY;
                // 使用css方法获取当前位置，避免position()在transform影响下的计算误差
                var left = parseInt($img.css('left')) || 0;
                var top = parseInt($img.css('top')) || 0;
                imageStartX = left;
                imageStartY = top;
                $img.css('cursor', 'grabbing');
                e.preventDefault();
            });
            
            $(document).off('mousemove.preview').on('mousemove.preview', function(e) {
                if (isDragging) {
                    var deltaX = e.clientX - dragStartX;
                    var deltaY = e.clientY - dragStartY;
                    var newX = imageStartX + deltaX;
                    var newY = imageStartY + deltaY;
                    $img.css({'left': newX + 'px', 'top': newY + 'px'});
                }
            });
            
            $(document).off('mouseup.preview').on('mouseup.preview', function() {
                if (isDragging) {
                    isDragging = false;
                    $img.css('cursor', 'grab');
                }
            });
        }
        
        // 禁用预览图片拖动
        function disableModalDrag() {
            $('#modalPreviewImage').css('cursor', 'grab');
            $('#modalPreviewImage').off('mousedown.preview');
            $(document).off('mousemove.preview mouseup.preview');
            isDragging = false;
        }
        
        // 切换到上一张图片
        function switchToPrevImage() {
            // 使用与按钮状态相同的有效性检查逻辑
            const isPrevIdValid = previousPictureId !== null && 
                                 previousPictureId !== undefined && 
                                 previousPictureId !== '' && 
                                 !isNaN(Number(previousPictureId));
                                 
            if (isPrevIdValid) {
                console.log("切换到上一张图片，ID:", previousPictureId);
                // 构建带查询参数的URL并跳转
                const url = buildUrlWithParams(ctx + "system/picture/historyDetail/" + previousPictureId, queryParams);
                window.location.href = url;
            } else {
                console.warn("无法切换到上一张图片：无效的图片ID", previousPictureId);
                // 即使按钮被禁用，用户仍可能通过其他方式触发，所以增加额外保护
            }
        }
        
        // 切换到下一张图片
        function switchToNextImage() {
            // 使用与按钮状态相同的有效性检查逻辑
            const isNextIdValid = nextPictureId !== null && 
                                 nextPictureId !== undefined && 
                                 nextPictureId !== '' && 
                                 !isNaN(Number(nextPictureId));
                                 
            if (isNextIdValid) {
                console.log("切换到下一张图片，ID:", nextPictureId);
                // 构建带查询参数的URL并跳转
                const url = buildUrlWithParams(ctx + "system/picture/historyDetail/" + nextPictureId, queryParams);
                window.location.href = url;
            } else {
                console.warn("无法切换到下一张图片：无效的图片ID", nextPictureId);
                // 即使按钮被禁用，用户仍可能通过其他方式触发，所以增加额外保护
            }
        }
        
        // 切换到指定ID的图片
        function switchToImage(newId) {
            // 增强的有效性检查
            const isNewIdValid = newId !== null && 
                               newId !== undefined && 
                               newId !== '' && 
                               !isNaN(Number(newId)) &&
                               newId !== pictureId;
                               
            if (isNewIdValid) {
                console.log("切换到指定图片，ID:", newId);
                // 构建带查询参数的URL并跳转
                const url = buildUrlWithParams(ctx + "system/picture/historyDetail/" + newId, queryParams);
                window.location.href = url;
            } else {
                console.warn("无法切换图片：无效的图片ID或与当前ID相同", newId);
            }
        }
        
        // 更新箭头按钮可用状态 - 增强有效性检查
        function updateArrowButtonsState() {
            // 严格检查ID有效性：不为null、不为undefined、不为空字符串且能转换为有效数字
            const isPrevIdValid = previousPictureId !== null && 
                                  previousPictureId !== undefined && 
                                  previousPictureId !== '' && 
                                  !isNaN(Number(previousPictureId));
            
            const isNextIdValid = nextPictureId !== null && 
                                  nextPictureId !== undefined && 
                                  nextPictureId !== '' && 
                                  !isNaN(Number(nextPictureId));
            
            $('#prevImageBtn').prop('disabled', !isPrevIdValid);
            $('#nextImageBtn').prop('disabled', !isNextIdValid);
        }
    </script>
</body>
</html>